package com.aerozhonghuan.logisticsmall.modules.home;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.aerozhonghuan.foundation.eventbus.EventBusManager;
import com.aerozhonghuan.logisticsmall.R;
import com.aerozhonghuan.logisticsmall.framework.DB.DBAdapter;
import com.aerozhonghuan.logisticsmall.framework.base.TitlebarFragment;
import com.aerozhonghuan.logisticsmall.modules.common.IMainView;
import com.aerozhonghuan.logisticsmall.modules.common.MainActivity;
import com.aerozhonghuan.logisticsmall.modules.common.entity.GoodsObject;
import com.aerozhonghuan.logisticsmall.modules.common.entity.ProductImg;
import com.aerozhonghuan.logisticsmall.modules.common.event.TabNumberChangedEvent;
import com.aerozhonghuan.logisticsmall.modules.home.beans.ActivityDetailBean;
import com.aerozhonghuan.logisticsmall.modules.home.logic.HomePageInfoRequest;
import com.aerozhonghuan.logisticsmall.utils.CommunityTool;
import com.aerozhonghuan.logisticsmall.utils.CommunityUtils;
import com.aerozhonghuan.logisticsmall.widget.ProgressDialogIndicator;
import com.aerozhonghuan.oknet2.CommonCallback;
import com.aerozhonghuan.oknet2.CommonMessage;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;

import java.util.List;

/**
 * Created by ChenLin on 2019/5/29 11:01.Email&WeChat:7877409@163.com
 * 活动详情页面
 */
public class ActivityDetailFragment extends TitlebarFragment {

    private View rootView;
    private String mId;
    private List<GoodsObject> mGoodsObjectList;
    private MyAdapter mMyAdapter;
    private Activity mActivity;
    private DBAdapter mDbAdapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mActivity = getActivity();
        mDbAdapter = new DBAdapter(getContext());
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_activity_detail, null);
            if (getArguments() == null || !getArguments().containsKey("id")) {
                alert("数据异常");
                mActivity.finish();
            }
            mId = getArguments().getString("id");
            initView();
            initData();
        }
        return rootView;
    }

    private void initView() {
        RecyclerView rv = (RecyclerView) rootView.findViewById(R.id.rv);
        mMyAdapter = new MyAdapter();
        rv.setLayoutManager(new LinearLayoutManager(getContext()));
        rv.setAdapter(mMyAdapter);
    }

    private void initData() {
        HomePageInfoRequest.activityDetail(mId, getContext(), new ProgressDialogIndicator(getContext()), new CommonCallback<ActivityDetailBean>() {
            @Override
            public void onSuccess(ActivityDetailBean messsageBodyObject, CommonMessage commonMessage, String allResponseString) {
                mGoodsObjectList = messsageBodyObject.datalist;
                LogUtils.i(mGoodsObjectList);
                mMyAdapter.notifyDataSetChanged();
            }
        });
    }

    class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//            return new MyHolder(View.inflate(parent.getContext(), R.layout.item_activity_detail, null));
            return new MyHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_activity_detail, parent, false));
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            ((MyHolder) holder).setData(mGoodsObjectList.get(position));
        }

        @Override
        public int getItemCount() {
            return mGoodsObjectList == null ? 0 : mGoodsObjectList.size();
        }
    }

    class MyHolder extends RecyclerView.ViewHolder {

        private TextView mBuy_size_text;
        private RequestOptions options;
        private Button mAdd_btn;
        private Button mMin_btn;
        private ImageView mIvImg;
        private TextView mTvName;
        private TextView mTvMoney;
        private GoodsObject goodsObject;

        MyHolder(View itemView) {
            super(itemView);
            options = new RequestOptions().placeholder(R.mipmap.ic_placehodler).error(R.mipmap.ic_placehodler);
            mIvImg = (ImageView) itemView.findViewById(R.id.iv_img);
            mTvName = (TextView) itemView.findViewById(R.id.tv_name);
            mTvMoney = (TextView) itemView.findViewById(R.id.tv_money);
            mMin_btn = (Button) itemView.findViewById(R.id.min_btn);
            mAdd_btn = (Button) itemView.findViewById(R.id.add_btn);
            mBuy_size_text = (TextView) itemView.findViewById(R.id.buy_size_text);
            itemView.findViewById(R.id.cl_content).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ActivityUtils.startActivity(new Intent(mActivity, GoodsDetailsActivity.class).putExtra("product", goodsObject));
                }
            });

            mMin_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int productCurNumber = goodsObject.getIntoGouwucheSize() - 1;
                    if (productCurNumber == 0) {
                        mAdd_btn.setSelected(false);
                        mBuy_size_text.setVisibility(View.INVISIBLE);
                        mMin_btn.setVisibility(View.INVISIBLE);
                        //删除购物车中该商品
                        mDbAdapter.deleteTitle(String.valueOf(goodsObject.getPvsid()));
                    } else {
                        mBuy_size_text.setText(productCurNumber + "");
                    }
                    goodsObject.setIntoGouwucheSize(productCurNumber);
                    mDbAdapter.open().updateGouwuche(goodsObject.getPvsid(), CommunityUtils.USER_ID, CommunityTool.saveObject(goodsObject));
                    int curGouwucheAllNumber = MainActivity.getCarNum() - 1;
                    if (curGouwucheAllNumber != 0) {
                        EventBusManager.post(new TabNumberChangedEvent(IMainView.TAB_CART_FRAGMENT, curGouwucheAllNumber));
                    }
                }
            });
            mAdd_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    v.setSelected(true);
                    int productSize = CommunityUtils.addProductToGouwuche(mActivity, goodsObject, new DBAdapter(mActivity), 0);
                    int pGouwucheSize = goodsObject.getIntoGouwucheSize();
                    if (pGouwucheSize <= goodsObject.getQuantityAvailable()) {
                        if (!mBuy_size_text.isShown()) {
                            mBuy_size_text.setVisibility(View.VISIBLE);
                            mMin_btn.setVisibility(View.VISIBLE);
                            mBuy_size_text.setText(pGouwucheSize + "");
                        } else {
                            mBuy_size_text.setText(pGouwucheSize + "");
                        }
                        EventBusManager.post(new TabNumberChangedEvent(IMainView.TAB_CART_FRAGMENT, productSize));
                    } else {
                        ToastUtils.showShort("库存不足了，先买这么多吧!");
                    }
                }
            });
        }

        public void setData(GoodsObject goodsObject) {
            this.goodsObject = goodsObject;
            mTvMoney.setText("¥ " + (goodsObject.getPrice()) / 100f);
            mTvName.setText(goodsObject.getBaseName());
            int productImgId = 0;
            List<ProductImg> productImgs = goodsObject.getpImageList();


            if (productImgs != null && productImgs.size() > 0) {
                for (ProductImg productImg : productImgs) {
                    if (productImg.is_thumbnail == 1) {
                        productImgId = productImg.imgid;
                        break;
                    } else {
                        productImgId = productImg.imgid;
                    }
                }
            }
            String imgUrl = CommunityTool.changeImageId(productImgId, true, false);
            Glide.with(ActivityDetailFragment.this.getActivity()).load(imgUrl).apply(options).into(mIvImg);
        }
    }
}
